<!-- 职位体系管理表格 -->
<template>
  <div
    class="main-list"
    style="
      display: flex;
      flex-direction: column;
      flex: 4;
      padding: 0 20px;
      overflow: auto;
    "
  >
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-space>
          <span>职位({{ flatData?.length }})</span>
          <span>|</span>
          <div>
            <a-dropdown
              :popup-max-height="false"
              v-model="treeLevel"
              @select="handleTreeLevelSelect"
            >
              <span style="cursor: pointer"
                >展开{{ treeLevel !== 4 ? treeLevel : '全部' }}级<icon-down
                  style="color: #165dff"
                />
              </span>
              <template #content>
                <a-doption :value="1">1级</a-doption>
                <a-doption :value="2">2级</a-doption>
                <a-doption :value="3">3级</a-doption>
                <a-doption :value="4">全部</a-doption>
              </template>
            </a-dropdown>
          </div>
        </a-space>
        <a-input-search
          :style="{ width: '320px' }"
          placeholder="请输入职位名称"
          search-button
          v-model="nameSearch"
          @search="onSearch"
          @press-enter="onSearch"
        >
          <template #button-icon>
            <icon-search />
          </template>
        </a-input-search>
        <a-button @click="reset">重置</a-button>
      </template>
      <template #right>
        <a-button type="primary" @click="add">新增职位</a-button>
        <a-button
          type="outline"
          class="commonBtns"
          @click="importVisible = true"
          >导入</a-button
        >
        <a-button
          type="outline"
          class="commonBtns"
          @click="exportSettingVisible = true"
          >导出<!--  --></a-button
        >
        <a-dropdown @select="moreControl" v-model="tableMethodType">
          <a-button type="outline"
            >更多操作
            <icon-down
              :style="{
                color: '#165dff',
                marginLeft: '5px'
              }"
            />
          </a-button>
          <template #content>
            <a-doption :value="1">批量启用</a-doption>
            <a-doption :value="2">批量停用</a-doption>
            <a-doption :value="3">批量删除</a-doption>
          </template>
        </a-dropdown>
      </template>
    </ConditionBox>

    <table-turn
      style="height: 100%"
      :table-data="getTableData"
      :args="args"
      ref="tableRef"
      :isShowPagination="false"
    >
      <TableControlShow
        :selectedHeader="selectedHeader"
        :showCtlCodeArr="showCtlCodeArr"
        :specialCtlCode="['C2818BAA63AE848AA845DA2E81ECB1843']"
      >
        <template #custom="record">
          <div
            v-if="
              record.controlData.ctlCode === 'C2818BAA63AE848AA845DA2E81ECB1843'
            "
            :style="{
              textAlign: 'left',
              paddingLeft:
                record.cellData.level > 2
                  ? '32px'
                  : (record.cellData.level - 1) * 16 + 'px',
              cursor: 'pointer'
            }"
          >
            <span
              @click="
                goDetail(
                  record.cellData.id,
                  record.cellData.useTemplate.ownerType
                )
              "
            >
              {{ record.cellData[record.controlData.ctlCode] }}</span
            >
          </div>
        </template>
      </TableControlShow>
      <a-table-column title="是否启用" :width="100" data-index="enable">
        <template #cell="{ record }">
          <a-tag
            class="enable"
            :color="
              record.enable === 1
                ? `rgb(var(--green-1))`
                : 'rgb(var(--danger-1))'
            "
            :style="{
              color:
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))',
              '--enable':
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))'
            }"
          >
            {{ record.enable === 1 ? '启用' : '停用' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column :width="100" fixed="right">
        <template #title>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-filter-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
              @click="isFilter"
            />
          </a-tooltip>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-setting-def"
              :size="26"
              :style="{
                cursor: 'pointer'
              }"
              @click="isHeaderSetting"
            />
          </a-tooltip>
        </template>
        <template #cell="{ record }">
          <a-space :size="0">
            <a-tooltip content="职位档案">
              <icon-font
                type="icon-details-def"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goDetail(record.id, record.useTemplate.ownerType)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm
                content="是否确认删除该条数据?"
                position="left"
                @ok="del(record.id)"
              >
                <icon-font
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
            <a-tooltip content="更多操作">
              <a-dropdown @select="moreTableItemControl">
                <icon-font
                  type="icon-more-def"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                  @click="singleControl(record)"
                />
                <template #content>
                  <a-doption :value="1">启用</a-doption>
                  <a-doption :value="2">停用</a-doption>
                  <a-doption :value="3">设置控编</a-doption>
                </template>
              </a-dropdown>
            </a-tooltip>
          </a-space>
        </template>
      </a-table-column>
    </table-turn>
  </div>
  <AddPosition
    v-model:visible="modalVisiable"
    @positionAddEmit="positionAddEmit"
  ></AddPosition>
  <FormHeaderControlSetting
    v-model:visible="setting"
    title="职位管理表头设置"
    :result-list="headerSetting"
    @headerSave="headerSave"
    :forbidList="forbidList"
    :orginHeaderList="orginHeaderList.headerListCode"
  ></FormHeaderControlSetting>
  <TableMethod
    v-model:visible="tableMethodVisible"
    :type="tableMethodType"
    @positionEmit="positionEmit"
  />
  <ControlEditing
    :type="2"
    v-model:visible="controlEditingVisible"
    :id="singleSelectId"
    @controlEditingEmit="controlEditingEmit"
    :data="controlEditingData"
  />
  <ExportControlSetting
    v-model:visible="exportSettingVisible"
    title="职位导出设置"
    :result-list="exportHeaderList"
    @headerSave="exportSave"
    :forbidList="exportyForbidList"
  >
  </ExportControlSetting>
  <ImportModal
    v-model:visible="importVisible"
    :func="getHeaderData"
    :headerList="headerSetting"
    :forbidList="importSelected"
    :forbidSelectedList="forbidSelectedList"
    @importSave="importSave"
    @importHeaderSave="importHeaderSave"
    title="职位导入"
  >
  </ImportModal>
</template>

<script lang="tsx" setup>
import {
  dataTreeFilter,
  controldataTreeFilter,
  flatTree,
  downloadExcelFile
} from '@/utils/utils';
import { GetJobTypeList } from '@/apis/management/organization/baseSetting';
import { GetlistData } from '@/apis/management/personnel/baseSetting/TransactionSetting';
import {
  PostPosition,
  PostPositionMerge,
  GetPosition,
  DelPosition,
  ChangePositionState,
  ExportPositionList,
  PostPositionStandard,
  ImportPositionList,
  PutPositionControlEditing
} from '@/apis/management/organization/positionManagement';
import { GetOrganizationList } from '@/apis/management/organization/organizationManagement';
import {
  GetPositionTypeList,
  GetPositionLevelList
} from '@/apis/management/organization/baseSetting';
import { GetJobList } from '@/apis/management/organization/positionManagement';
import {
  PostImportTemplate,
  GetHeaderSetting,
  PostHeaderSetting,
  PutHeaderSetting
} from '@/apis/management/base';
import { GetBusinessModalData } from '@/apis/controltotal';
import AddPosition from './Components/AddDrawer/index.vue';
import TableMethod from './Components/TableMethod/index.vue';
import { Message, Modal } from '@arco-design/web-vue';
import mitter from '@/utils/mitt';

const router = useRouter();

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  },
  stripe: true,
  indentSize: 0
});

let treeLevel = ref(3); // 展开多少层子树，初始展开3层

// 选择展开子树层级事件
const handleTreeLevelSelect = (val: number) => {
  treeLevel.value = val;
};

// 处理数据展开层级
const handleLevel = () => {
  tableRef.value.currExpandedKeys = [];
  flatData.value.forEach((item: any) => {
    if (item.level < 4) {
      if (item.level < treeLevel.value)
        tableRef.value.currExpandedKeys.push(item.id);
    } else {
      tableRef.value.currExpandedKeys.push(item.id);
    }
  });
};

watch(
  () => treeLevel.value,
  (val) => {
    handleLevel();
  }
);

// 新增表头
const addHeader = async () => {
  try {
    const {
      funcCtlInfos: { children }
    } = (await GetBusinessModalData({
      funcCode: 'SER_FUNCE54A4F24B2A6453A8A4B8E9397C36A63'
    })) as any;

    let headerListCode: any = [];
    children.forEach((item1: any) => {
      const { subRelDetail, cnName, subCode } = item1.subDetail;
      subRelDetail?.forEach((item2: any, index2: number) => {
        headerListCode.push(item2.ctlCode);
      });
    });
    await PostHeaderSetting({
      userId: +(localStorage.getItem('userId') as string),
      ownerFuncType: 2,
      headerListCode: headerListCode.join(',')
    });

    getData();
  } catch (error: unknown) {
    console.log(error);
  }
};

let tableRef = ref(); // 储存table的ref

let modalVisiable = ref(false); // 判断是否点击新增按钮

// const dataFilter = (data: any) => {
//   const arr = data.map((item: any) => ({
//     ...item,
//     ...controldataTreeFilter(item.ctlValue)
//   }));
//   return arr;
// };
const nameSearch = ref(''); // 储存职位名称
let positionType = ref(''); // 储存旁边导航栏的职位类型
onMounted(() => {
  // 响应旁边导航栏点击查找对应的职位类型
  mitter.on('positionTreeSelect1', (res: any) => {
    positionType.value = res;
    nextTick(() => {
      tableRef.value.loadData();
    });
  });
});

// 根据职位名称模糊搜索过滤函数
const maptree = (treeData: any, val: string) => {
  let filteredData: any = [];
  treeData.forEach((node: any) => {
    // 如果是职位名称C30BBF36A5AF541F7A2657671DEE2EDD6
    if (node['C2818BAA63AE848AA845DA2E81ECB1843'].includes(val)) {
      filteredData.push(node);
    } else {
      if (node.children && node.children.length > 0) {
        let filteredChildren = maptree(node.children, val);
        if (filteredChildren.length > 0) {
          let updatedNode = {
            ...node,
            children: filteredChildren
          };
          filteredData.push(updatedNode);
        }
      }
    }
  });
  return filteredData;
};
let flatData = ref(); //
// 获取表格数据
const getTableData = async (pageData?: any) => {
  try {
    const res: any = await GetPosition({
      pageNumber: 0,
      pageSize: -1,
      typeName: positionType.value
    });
    res.content = maptree(dataTreeFilter(res.content, ''), nameSearch.value);
    flatData.value = flatTree(dataTreeFilter(res.content));
    // 默认展开3层
    handleLevel();
    return Promise.resolve(res.content);
  } catch (error: unknown) {
    console.log(error);
  }
};
// 搜索框
const onSearch = () => {
  tableRef.value.loadData({
    pageNumber: 0,
    pageSize: -1
  });
};

// 重置搜索框
const reset = () => {
  nameSearch.value = '';
  positionType.value = '';
  tableRef.value.loadData();

  // 重置侧边栏选中的数据
  mitter.emit('resetPositionTree');
};

let setting = ref(false); // 判断是否点击设置按钮
let headerList = ref(); // 接口获取过来的原始表头数据
let headerSetting = ref<any>([]); // 当前的表头数据
let orginHeaderList = ref([]); // 原始的表头数据
let positionTypeList = ref([]); // 储存当前职位类型数据
let deptList = ref([]); // 部门类型数据
let jobList = ref([]); // 职务类型
let positionLevelList = ref([]); // 职位层级数据
let forbidList = [
  'C2818BAA63AE848AA845DA2E81ECB1843',
  'C63EC32DCE9CC4BE6AC7649E23234A542',
  'CB25F6DA9F83C4424BBC37E8756BB871E'
]; // 必选的表头 职位名称，职位类型, 职位编码

const getData = async () => {
  try {
    const userId = Number(localStorage.getItem('userId'));
    const [
      headerSettingRes,
      positionTypeListRes,
      deptListRes,
      jobListRes,
      positionLevelListRes,
      businessModalDataRes
    ] = await Promise.all([
      // 获取职位类型数据
      GetHeaderSetting({ ownerFuncType: 2, userId }),
      GetPositionTypeList({}),
      // 获取部门类型
      GetOrganizationList({}),
      // 获取职务管理数据
      GetJobList({
        pageNumber: 0,
        pageSize: -1
      }),
      // 获取职位层级数据
      GetPositionLevelList({
        pageNumber: 0,
        pageSize: -1
      }),
      // 获取职位控件数据
      GetBusinessModalData({
        funcCode: 'SER_FUNCE54A4F24B2A6453A8A4B8E9397C36A63'
      })
    ]);
    orginHeaderList.value = headerSettingRes;
    headerSetting.value = [];
    const headerChildren = businessModalDataRes.funcCtlInfos.children;
    headerChildren.forEach((child: any, index: number) => {
      headerSetting.value.push({
        collectionName: child.subDetail.cnName,
        collectionCode: child.subDetail.subCode,
        heads: child.subDetail.subRelDetail.map((subDetail: any) => {
          const isDefault = headerSettingRes.headerListCode.includes(
            subDetail.ctlCode
          );
          return {
            ...subDetail,
            isDefault
          };
        })
      });
    });
    exportHeaderList.value = headerSetting.value;

    if (headerSettingRes.headerListCode.length < 1) {
      addHeader();
    }
    positionTypeList.value = flatTree(positionTypeListRes.positionCategoryList);
    deptList.value = flatTree(deptListRes);
    jobList.value = jobListRes.content;
    positionLevelList.value = positionLevelListRes.content;
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

// 新增
const add = () => {
  modalVisiable.value = true;
};

// 是否显示表头
const isHeaderSetting = async () => {
  try {
    const { header } = await GetHeaderSetting({
      type: 2,
      userId: +(localStorage.getItem('userId') as string)
    });
    headerList.value = header;
    setting.value = !setting.value;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 在表格上显示的表头
const selectedHeader = computed(() => {
  const selectedHeaders: any[] = [];
  headerSetting.value.forEach((headerGroup: any, index: number) => {
    let defaultHeaders = headerGroup.heads.filter(
      (header: any) => header.isDefault === true
    );
    defaultHeaders = defaultHeaders.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.ctlCode);
      return {
        ...el,
        sort
      };
    });
    selectedHeaders.push(...defaultHeaders);
  });
  selectedHeaders.sort((a, b) => a.sort - b.sort);

  // 将职位名称移到最前面
  const nameHeaderIndex = selectedHeaders.findIndex(
    (header) => header.ctlCode === 'C2818BAA63AE848AA845DA2E81ECB1843'
  );
  if (nameHeaderIndex !== -1) {
    selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
  }

  return selectedHeaders;
});
// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    const id = orginHeaderList.value.id;
    const headerListCode = used.map((item: any) => item.ctlCode).join(',');
    await PutHeaderSetting({
      id,
      userId: +localStorage.getItem('userId')!,
      ownerFuncType: 2,
      headerListCode
    });
    headerSetting.value = totalList;
    orginHeaderList.value.headerListCode = headerListCode;
  } catch (error) {
    console.log(error);
  }
};

// 表格中需要特殊渲染的template
const showCtlCodeArr = [
  'C63EC32DCE9CC4BE6AC7649E23234A542',
  'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC',
  'CB4163C72FA5E45D38302983E8A66801E',
  'CE183DF5A547A4728A60F9AFDF3C53194',
  'CA8ABCC1480744557B3014C3454465A7E',
  'CED44AC9966904CD1AB546D309903727C',
  'C1F5AA49A78EC4B4FBD487F4D5887E576',
  'C50267C6B8E104B0C91EDD25BCAE35609'
];

// 处理特殊渲染的数据
const ShowInfo = (props: any) => {
  const record = props.record;
  const ctlCode = props.ctlCode;
  switch (ctlCode) {
    // 职位类别
    case 'C63EC32DCE9CC4BE6AC7649E23234A542':
      return (
        <div>
          {
            positionTypeList.value.find(
              (item: any) =>
                item.id == record['C63EC32DCE9CC4BE6AC7649E23234A542']
            )?.name
          }
        </div>
      );
    // 职位层级
    case 'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC':
      return (
        <div>
          {
            positionLevelList.value.find(
              (item: any) =>
                item.id == record['C9A9EF3DFFFC84AAFB97443DEE8E5B8CC']
            )?.name
          }
        </div>
      );
    // 是否特殊工种
    case 'CB4163C72FA5E45D38302983E8A66801E':
      return <div>{record.positonSpecialProfession === 1 ? '是' : '否'}</div>;
    // 是否关键职位
    case 'CE183DF5A547A4728A60F9AFDF3C53194':
      return <div>{record.positonKeyJob === 1 ? '是' : '否'}</div>;
    // 公司
    case 'CA8ABCC1480744557B3014C3454465A7E':
      return (
        <div>
          {
            deptList.value.find(
              (item: any) =>
                item.id == record['CA8ABCC1480744557B3014C3454465A7E']
            )?.name
          }
        </div>
      );
    // 职位所属部门
    case 'CED44AC9966904CD1AB546D309903727C':
      return (
        <div>
          {
            deptList.value.find(
              (item: any) =>
                item.id == record['CED44AC9966904CD1AB546D309903727C']
            )?.name
          }
        </div>
      );
    // 关联职务
    case 'C1F5AA49A78EC4B4FBD487F4D5887E576':
      return (
        <div>
          {
            jobList.value.find(
              (item: any) =>
                item.id == record['C1F5AA49A78EC4B4FBD487F4D5887E576']
            )?.name
          }
        </div>
      );
    // 是否设为标准职位
    case 'C50267C6B8E104B0C91EDD25BCAE35609':
      return <div>{record.positionSetStandPosition === 1 ? '是' : '否'}</div>;
    default:
      break;
  }
};

// 将控件赋值
const pushControl = (
  organizationTemplateCtlValue: any,
  templateId: number,
  collectionData: any,
  controlData: any,
  value: any
) => {
  organizationTemplateCtlValue.push({
    templateId,
    subCode: collectionData.subCode,
    subId: collectionData.id,
    ctlCode: controlData.ctlCode,
    ctlId: controlData.id,
    ctlValue: String(value)
  });
};

// 如果用户生成职位的同时同时选择新增为标准职位
const isAddPositionStand = async (formData: any, templateDetail: any) => {
  const positionLibraryReq = templateDetail.map(
    (item1: any, index1: number) => {
      const temp = formData;
      const templateId = item1.id;

      const positionLibrary = {
        ...temp,
        templateUseId: templateId
      };
      const organizationTemplateCtlValue: any = [];

      item1.collectionModel.forEach((item2: any) => {
        item2.controlModel.forEach((item3: any) => {
          switch (item3.ctlCode) {
            // 职位名称
            case 'C2818BAA63AE848AA845DA2E81ECB1843':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.name
              );
              break;
            // 职位编码
            case 'CB25F6DA9F83C4424BBC37E8756BB871E':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.positionCode
              );
              break;
            // 职位类别
            case 'C63EC32DCE9CC4BE6AC7649E23234A542':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.positionTypeId
              );
              break;
            // 直接上级职位
            case 'C3E117B6097E84B7B87A5572D8EFBEC46':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.upPosition
              );
              break;
            // 职位层级
            case 'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.positionLevelId
              );
              break;
            // 职级范围
            case 'C8D53C139F7B44D38826E0B5A3F9F93E1':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.positionRange
              );
              break;
            // 是否特殊工种
            case 'CB4163C72FA5E45D38302983E8A66801E':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.isSpecial
              );
              break;
            // 是否关键职位
            case 'CE183DF5A547A4728A60F9AFDF3C53194':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.isKey
              );
              break;
            // 职位使命
            case 'C1F70705F5EF84FB6A82892CD4181738C':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.remark
              );
              break;
            default:
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                ''
              );
              break;
          }
        });
      });
      return {
        positionLibrary,
        organizationTemplateCtlValue
      };
    }
  );
  await PostPositionStandard({
    positionLibraryReq
  });
};

// 新增组织弹出框自定义事件
const positionAddEmit = async (formData: any) => {
  try {
    // 获取对应模板
    const templateDetail = await PostPositionMerge({
      ids: [formData.templateId],
      ownerType: 2 // 职位模板默认传2
    });

    const jobListTemplateReq = templateDetail.map(
      (item1: any, index1: number) => {
        const temp = formData;
        const templateId = item1.id;

        const positionListModel = {
          ...temp,
          templateUseId: templateId,
          controlType: 1 // 编制类型，新增默认不编制传1
        };
        const organizationTemplateCtlValue: any = [];

        item1.collectionModel.forEach((item2: any) => {
          item2.controlModel.forEach((item3: any) => {
            switch (item3.ctlCode) {
              // 职位名称
              case 'C2818BAA63AE848AA845DA2E81ECB1843':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.name
                );
                break;
              // case 'POSITON_STAND_NAME':
              //   pushControl(formData, item2, templateId, formData.);
              //   break;
              // 职位编码
              case 'CB25F6DA9F83C4424BBC37E8756BB871E':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.positionCode
                );
                break;

              // 编制人数
              case 'CD25749DBA68E4BF3BCA616DD63751CB7':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.headcount
                );
                break;
              // 职位类别
              case 'C63EC32DCE9CC4BE6AC7649E23234A542':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.positionTypeId
                );
                break;
              // 职位层级
              case 'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.positionLevelId
                );
                break;
              // 职位层级
              case 'C8D53C139F7B44D38826E0B5A3F9F93E1':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.positionRange
                );
                break;
              // 是否特殊工种
              case 'CB4163C72FA5E45D38302983E8A66801E':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.isSpecial
                );
                break;
              // 是否关键职位
              case 'CE183DF5A547A4728A60F9AFDF3C53194':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.isKey
                );
                break;
              // 职位使命
              case 'C1F70705F5EF84FB6A82892CD4181738C':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.remark
                );
                break;
              // 公司
              case 'CA8ABCC1480744557B3014C3454465A7E':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.companyId
                );
                break;
              // 部门
              case 'CED44AC9966904CD1AB546D309903727C':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.organizationId
                );
                break;
              // 关联职务
              case 'C1F5AA49A78EC4B4FBD487F4D5887E576':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.relatedId
                );
                break;
              // 关联标准职位
              case 'C456DF4781B0F465F850C271F29504B1C':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.standJobId
                );
                break;
              // 选择职位说明书模板
              case 'C8B68CCFE6DAB49D088E663E467BFAB34':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.templateId
                );
                break;
              // 职位序列
              case 'CC0DAA8E0695A48489672B3E3B4DE8F1B':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.positionSequenceId
                );
                break;
              // 是否设为标准职位
              case 'C50267C6B8E104B0C91EDD25BCAE35609':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.isStand
                );
                break;
              default:
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  ''
                );
                break;
            }
          });
        });
        return {
          positionListModel,
          organizationTemplateCtlValue
        };
      }
    );
    await PostPosition({
      jobListTemplateReq
    });

    // 如果新增标准职位
    if (formData.isStand === 1)
      await isAddPositionStand(formData, templateDetail);

    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};

/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

// 前往对应的档案详情
const goDetail = (id: number, ownerType: number) => {
  router.push({
    name: 'PositionFileDetail',
    query: {
      id,
      ownerType
    }
  });
};

// 修改职位启用状态
const changeState = async (enable: number) => {
  try {
    let ids = [];
    if (isMoreSelect.value) ids = selectedList.value;
    else ids = [singleSelectId];
    await ChangePositionState({ ids, enable });
    tableRef.value.selectedList = [];
    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 删除
const del = async (id: number | null) => {
  try {
    if (!id) {
      await DelPosition({
        ids: selectedList.value
      });
      tableRef.value.selectedList = [];
      tableRef.value.loadData();
    } else {
      await DelPosition({
        ids: [id]
      });
      tableRef.value.selectedList = [];
      tableRef.value.loadData();
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

let singleSelectId = 0; // 储存单个item移动、合并的id
let singleSelectData = {}; // 储存单个item移动、合并的值
let isMoreSelect = ref(false); // 是否批量操作

const singleControl = (record: any) => {
  singleSelectData = record;
  singleSelectId = record.id;
  isMoreSelect.value = false;
};

const moreTableItemControl = (key: number) => {
  switch (key) {
    // 启用
    case 1:
      tableMethodType.value = key;
      tableMethodVisible.value = true;
      // changeState(1, singleSelectId);
      break;
    case 2:
      tableMethodType.value = key;
      tableMethodVisible.value = true;
      // changeState(2, singleSelectId);
      break;
    case 3:
      controlEdit();
      break;
    default:
      break;
  }
};

let controlEditingVisible = ref(false), // 是否显示控编弹窗
  controlEditingData = ref({
    controlType: 1, // 1 不控编 2非严格控编 3严格控编
    nonStrict: {
      percentage: undefined, // 非严格控编百分比
      warning: undefined // 非严格控编预警
    },
    strict: {
      warning: undefined // 严格控编预警
    }
  }); // 控编数据

// 点击设置控编的操作
const controlEdit = () => {
  const { controlType } = singleSelectData;
  controlEditingData.value.controlType = controlType;
  if (controlType === 2) {
    controlEditingData.value.nonStrict.percentage = singleSelectData.percentage;
    controlEditingData.value.nonStrict.warning = singleSelectData.warning;
  } else if (controlType === 3) {
    controlEditingData.value.strict.warning = singleSelectData.warning;
  }
  controlEditingVisible.value = true;
};
// 设置组织控编自定义事件
const controlEditingEmit = async (data: any) => {
  try {
    if (data) await PutPositionControlEditing(data);
    controlEditingData.value = {
      controlType: 1, // 1 不控编 2非严格控编 3严格控编
      nonStrict: {
        percentage: undefined, // 非严格控编百分比
        warning: undefined // 非严格控编预警
      },
      strict: {
        warning: undefined // 严格控编预警
      }
    };
    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};

let tableMethodVisible = ref(false), // 更多操作弹出框
  tableMethodType = ref(0); // 传进去的type

// 判断是否显示更多操作弹出框
const moreControl = (val: number) => {
  if (selectedList.value.length === 0) {
    Message.error('请至少选择一项！');
    return;
  }
  isMoreSelect.value = true;
  tableMethodType.value = val;
  tableMethodVisible.value = true;
};

// 更多弹出框自定义事件
const positionEmit = (type: number) => {
  switch (type) {
    // 批量启用
    case 1:
      changeState(1);
      break;
    // 批量停用
    case 2:
      changeState(2);
      break;
    case 3:
      del(null);
      break;
    default:
      break;
  }
  tableRef.value.loadData();
};

const getHeaderData = () => {
  try {
    // 获取表头
    return GetHeaderSetting({
      type: 2,
      userId: +(localStorage.getItem('userId') as string)
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

let importVisible = ref(false); // 导入弹出框
// 不选择的导入导出模板字段
// 职位编码， 标准职位
const forbidSelectedList = [
  'CB25F6DA9F83C4424BBC37E8756BB871E',
  'CF33E657A5EB849BD98CD5C9B5FDCCDCA'
];
const importSelected = [
  'C2818BAA63AE848AA845DA2E81ECB1843',
  'C63EC32DCE9CC4BE6AC7649E23234A542',
  'CB25F6DA9F83C4424BBC37E8756BB871E',
  'CA8ABCC1480744557B3014C3454465A7E',
  'CED44AC9966904CD1AB546D309903727C',
  'CD25749DBA68E4BF3BCA616DD63751CB7',
  'C1F5AA49A78EC4B4FBD487F4D5887E576',
  'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC',
  'C8D53C139F7B44D38826E0B5A3F9F93E1'
]; // 必选的表头 职位名称，职位类型, 职位编码,公司，部门，编制人数，关联职务，职位层级，职级范围，·
// 下载导入模板
const importHeaderSave = async (used: any, userId: number) => {
  try {
    // let excels: any = [];
    let code: any = [],
      name: any = [],
      necessary: any = [];
    used.forEach((item: any) => {
      code.push(item.code);
      name.push(item.name);
      if (importSelected.includes(item.code)) necessary.push('true');
      else necessary.push('false');
    });
    const formData = new FormData();
    formData.append('code', code + '');
    formData.append('name', name + '');
    formData.append('necessary', necessary + '');
    const res = await PostImportTemplate(formData);
    downloadExcelFile(res, '职位导入模板');
  } catch (error: unknown) {
    console.log(error);
  }
};

// 导入模板
const importSave = async (file: any) => {
  try {
    let formData = new FormData();
    formData.append('data', file.file);
    const res = await ImportPositionList(formData);
    if (res.code === 400) {
      Message.error(`${res.data}`);
    } else {
      Message.success('导入成功！');
      tableRef.value.loadData();
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

let exportSettingVisible = ref(false);
let exportHeaderList = ref(); // 接口获取过来的原始表头数据

let exportyForbidList = [
  'C7341027925C943708F3AEF98703ECC47',
  'C63EC32DCE9CC4BE6AC7649E23234A542',
  'CB25F6DA9F83C4424BBC37E8756BB871E'
]; // 必选的表头 职位名称，职位类型, 职位编码)

// 导出自定义事件
const exportSave = async (used: any) => {
  try {
    if (selectedList.value.length === 0) {
      Message.error('请至少选择一项导出！');
      return;
    } else {
      let code: any = [],
        name: any = [];
      used.forEach((item: any) => {
        code.push(item.code);
        name.push(item.name);
      });
      const formData = new FormData();
      formData.append('code', code + '');
      formData.append('name', name + '');
      formData.append('ids', selectedList.value + '');
      const res = await ExportPositionList(formData);
      if (selectedList.value.length === 1) {
        downloadExcelFile(res, `${selectedListData.value[0].name}职位信息导出`);
      } else {
        downloadExcelFile(
          res,
          `${selectedListData.value[0].name}等职位信息导出`
        );
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
</script>

<style scoped lang="less">
.header {
  display: flex;
  justify-content: end;
  align-items: center;
  margin-bottom: 20px;
  height: 35px;
  &-front {
    position: relative;
    line-height: 30px;
    margin-right: 20px;
  }
}
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}

:deep(.arco-table .arco-spin) {
  height: calc(100% - 1px);
}
:deep(.arco-table-container) {
  height: 100%;
}
</style>
